import requests
import json,time
from fastapi import FastAPI, HTTPException, Security,Depends,Body,APIRouter
import uuid
import function,DEwarehouse
from Crypto.Cipher import PKCS1_v1_5 as Cipher_pksc1_v1_5
from Crypto.PublicKey import RSA
import base64
import json
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
#易境通海外仓对接
#https://szy.kjwlxt.com/hwc_books3/#kucun_list
# 易境通海外仓
# https://erp.pelican-logistics.com/hwc_api

# 注意：请将 BASE_URL 修改为实际 API 域名，现使用正式地址路径
BASE_URL = "https://erp.pelican-logistics.com/hwc_api"

# 文档要求使用的秘钥（token）
HWC_TOKEN = "f068147c66d6ac647ea6494ae7e39867"
router = APIRouter()


# 接口的AES加解密
class Encrypt:
    def __init__(self, key):
        # 将密钥解码为bytes，确保长度符合AES要求
        key = base64.b64decode(key.encode())
        # 创建 AES 加密器（使用 ECB 模式）
        self.cipher = AES.new(key, AES.MODE_ECB)

    # AES 加密
    def aes_encrypt(self, plaintext):
        data = json.dumps(plaintext)
        # 使用PKCS7填充方式
        plaintext_code = pad(data.encode("utf-8"), AES.block_size)
        # 加密数据
        ciphertext = self.cipher.encrypt(plaintext_code)
        # 将加密结果转为Base64 字符串
        encrypted_text = base64.b64encode(ciphertext).decode()
        return encrypted_text

    # AES 解密
    def aes_decrypt(self, data) -> json:
        # 将Base64解码的数据解码为bytes
        raw = base64.b64decode(data.encode())
        # 解密数据并移除填充
        decrypted_data = unpad(self.cipher.decrypt(raw), AES.block_size)
        loads = decrypted_data.decode("utf-8-sig")
        return json.loads(loads)



appId = '90a4e58e7dc64a468306967b1a5ac14d'
appSecert = '5eUNzUmpWStMrGKP1pxqKg=='
Server_url = 'https://oms-openapi.wydgroup.com'




@router.get("/get_product_from_MW2DE/",summary='获取德国易境通海外仓的产品列表')
async def get_product_from_MW2DE():
    port = '/oms/openapi/goods/v1/goods/queryPage'

    headers = {"Content-Type": "application/json"}
    json_temp = {
        "goodsType": "1",
        "modifyTimeEnd": "",
        "modifyTimeStart": "",
        "pageNum": 1,
        "pageSize": 100,
        "status": "2"
    }
    current_timestamp = time.time()
    aes = Encrypt(appSecert)
    temp = aes.aes_encrypt(json_temp)
    print("打印加密json:", temp)
    val_param = {
        "uniqueNo": "37f55f1f-c0ae-45d1-a8e1-3f00f8f29bc01112211",
        "source": "ENDI",
        "body": temp,
        "timezoneOffset": "8",
        "appId": appId,
        "timestamp": current_timestamp
    }
    print("参数：", val_param)
    sst1 = requests.post(url=Server_url + port, json=val_param, headers=headers)
    result = sst1.json()
    print("打印请求结果：", result['data'])
    sst2 = aes.aes_decrypt(result['data'])
    return_arr = []
    for row in sst2['records']:
        return_arr.append(row)

    return return_arr


#【产品管理】新增 易境通海外仓
def add_new_sku_WYD(Seller_SKU,ANSI,price,isCharged='0',packingFlag='0',packingHeight=10,packingLength=10,packingWidth=10,packingWeight=1):
    port = '/oms/openapi/goods/v1/goods/create'
    headers = {"Content-Type": "application/json"}
    json_temp = {
        "categoryCode": "1b387bb41f8311ecaef0b083fe90c14a",
        "chineseName": Seller_SKU,
        "codeList": [{"code": ANSI,"isMain": "1","type": "1"}],
        "declarePrice": price,
        "declarePriceUnit": "GBP",
        "englishName": Seller_SKU,
        "isCharged": isCharged,
        "packingFlag": packingFlag,
        "packingHeight": packingHeight,
        "packingLength": packingLength,
        "packingWeight": packingWeight,
        "packingType": "01",
        "packingWidth":  packingWidth
    }

    current_timestamp = time.time()
    aes = Encrypt(appSecert)
    tempNo = str(uuid.uuid4())
    temp = aes.aes_encrypt(json_temp)
    print("打印加密json:", temp)
    val_param = {
        "uniqueNo": tempNo,
        "source": "ENDI",
        "body": temp,
        "timezoneOffset": "8",
        "appId": appId,
        "timestamp": current_timestamp
    }
    print("参数：", val_param)
    sst1 = requests.post(url=Server_url + port, json=val_param, headers=headers)
    print("返回：",sst1.text)
    result = sst1.json()
    print("打印请求结果：", result['data'])
    sst2 = aes.aes_decrypt(result['data'])
    print(sst2)
    return_arr = sst2
    return return_arr

@router.get("/add_new_SUK_MW2DE_WYD/", summary='【产品管理】新增 ')
async def get_all_stocks(Seller_SKU,ANSI,price,isCharged='0',packingFlag='0',packingHeight=10,packingLength=10,packingWidth=10,packingWeight=1):
    return add_new_sku_WYD(Seller_SKU,ANSI,price,isCharged,packingFlag,packingHeight,packingLength,packingWidth,packingWeight)


def get_stocks_MW2DE():
    port = '/oms/openapi/stock/v1/warehouseInventory/query'
    headers = {"Content-Type": "application/json"}
    json_temp = {
        "inventoryWarnStatus": "0",
        "pageNo": 1,
        "pageSize": 100,
        "sku": "",
        "warehouseCode": ""
    }
    current_timestamp = time.time()
    aes = Encrypt(appSecert)
    temp = aes.aes_encrypt(json_temp)
    tempNo = str(uuid.uuid4())
    print("uuid:", tempNo)
    print("打印加密json:", temp)
    val_param = {
        "uniqueNo": tempNo,
        "source": "ENDI",
        "body": temp,
        "timezoneOffset": "8",
        "appId": appId,
        "timestamp": current_timestamp
    }
    print("参数：", val_param)
    sst1 = requests.post(url=Server_url + port, json=val_param, headers=headers)
    result = sst1.json()
    print("打印请求结果：", result['data'])
    sst2 = aes.aes_decrypt(result['data'])
    print("解密后的：", sst2)
    return_arr = []
    for row in sst2['records']:
        sellerSKU = row['englishName']
        QTY = row['inventoryAvailableNum']
        asin = row['masterSku']
        inventoryTransportationNum = row['inventoryTransportationNum']
        temp = {"sellerSKU": sellerSKU, "QTY": QTY, "asin": asin, "TransportationNum": inventoryTransportationNum}
        return_arr.append(temp)

    return return_arr


@router.get("/get_stocks_from_MW2DE/",summary='获取德国易境通海外仓的库存')
async def get_stocks_from_MW2DE():
    return  get_stocks_MW2DE()


#入库数据查询
def inbound_queryPage_wyd(inboundStatus='1'):
    # 入库单状态(0 - 待提交
    # 1 - 在途中
    # 2 - 收货中
    # 3 - 收货完成
    # 4 - 已作废
    # 5 - 待处理
    # 6 - 处理中
    # 7 - 处理完成
    # 9 - 上架完成)
    port = '/oms/openapi/inbound/v1/inbound/queryPage'
    headers = {"Content-Type": "application/json"}
    json_temp = {
          "billNum": "",
          "dateType": "",
          "endDate": "",
          "inboundStatus": inboundStatus,
          "pageNo": 1,
          "pageSize": 100,
          "skuNo": "",
          "startDate": ""
        }
    current_timestamp = time.time()
    aes = Encrypt(appSecert)
    temp = aes.aes_encrypt(json_temp)
    tempNo = str(uuid.uuid4())
    print("uuid:", tempNo)
    print("打印加密json:", temp)
    val_param = {
        "uniqueNo": tempNo,
        "source": "ENDI",
        "body": temp,
        "timezoneOffset": "8",
        "appId": appId,
        "timestamp": current_timestamp
    }
    print("参数：", val_param)
    sst1 = requests.post(url=Server_url + port, json=val_param, headers=headers)
    result = sst1.json()
    print("打印请求结果：", result['data'])
    sst2 = aes.aes_decrypt(result['data'])
    print("解密后的：", sst2)
    return_arr = sst2['records']
    return return_arr

@router.get("/inbound_queryPage/",summary='易境通海外仓入库情况列表请求')
async def get_stocks_from_MW2DE_temp(inboundStatus='1'):
    return inbound_queryPage_wyd()

